import { useStore } from '@/stores';
import { cloneDeep, throttle } from 'lodash';
import { Ref, inject, onMounted, onUnmounted, provide, reactive, ref } from 'vue';

export const useInterval = (fn, time = 1000 * 60, immediately = false) => {
  const clearFlag = ref();
  onMounted(() => {
    if (immediately) fn();
    clearFlag.value = setInterval(() => fn(), time);
  });
  onUnmounted(() => {
    clearInterval(clearFlag.value);
  });
};

export const useThrottle = (fn, time) => {
  const throttled = throttle(fn, time);

  onUnmounted(() => {
    if (throttled) throttled.cancel();
  });

  return throttled;
};

export const useWindowResize = (fn, time = 100) => {
  const _fn = useThrottle(fn, time);
  onMounted(() => {
    _fn();
    window.addEventListener('resize', _fn);
  });
  onUnmounted(() => {
    window.removeEventListener('resize', _fn);
  });
};

export const usePageNavi = (title: string) => {
  const path = inject<Ref<string[]>>('page-navi-path');
  if (path) {
    path.value.push(title);
    onUnmounted(() => path.value.pop());
  } else {
    const path = ref([title]);
    provide('page-navi-path', path);
  }
};

export const useData = <T extends Record<string, any>>(defaultData) => {
  const data = reactive<T>(cloneDeep(defaultData));

  const revertDefaultData = (data, defaultData) => {
    const _data = cloneDeep(defaultData);
    for (const key in data) {
      if (Object.prototype.hasOwnProperty.call(data, key)) {
        data[key] = _data[key];
      }
    }
  };

  const resetData = (value?: T) => revertDefaultData(data, value || defaultData);

  return [data, resetData] as [T, (value?: T) => void];
};

export const useUserWhiteList = (key: string, list: string[]) => {
  const store = useStore();
  const userSet = new Set(list);
  return userSet.has(store.userInfo[key]);
};
